package com.exchange.service;

import com.exchange.entity.DeliveryTracking;
import com.exchange.entity.Order;
import com.exchange.repository.DeliveryTrackingRepository;
import com.exchange.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeliveryService {
    
    @Autowired
    private DeliveryTrackingRepository deliveryTrackingRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    public List<DeliveryTracking> getDeliveryHistory(Long orderId) {
        return deliveryTrackingRepository.findByOrderIdOrderByTimestampDesc(orderId);
    }
    
    public DeliveryTracking addDeliveryUpdate(Long orderId, String trackingNumber, String deliveryCompany, 
                                           String status, String location, String details) {
        // Verify that the order exists
        if (!orderRepository.existsById(orderId)) {
            throw new RuntimeException("Order not found");
        }
        
        DeliveryTracking deliveryUpdate = new DeliveryTracking();
        deliveryUpdate.setOrderId(orderId);
        deliveryUpdate.setTrackingNumber(trackingNumber);
        deliveryUpdate.setDeliveryCompany(deliveryCompany);
        deliveryUpdate.setStatus(status);
        deliveryUpdate.setLocation(location);
        deliveryUpdate.setDetails(details);
        
        return deliveryTrackingRepository.save(deliveryUpdate);
    }
    
    public DeliveryTracking updateOrderDeliveryStatus(Long orderId, String newStatus) {
        // Find the most recent delivery tracking record for this order
        List<DeliveryTracking> deliveries = deliveryTrackingRepository.findByOrderIdOrderByTimestampDesc(orderId);
        
        if (!deliveries.isEmpty()) {
            DeliveryTracking latestDelivery = deliveries.get(0);
            latestDelivery.setStatus(newStatus);
            latestDelivery.setTimestamp(java.time.LocalDateTime.now());
            return deliveryTrackingRepository.save(latestDelivery);
        }
        
        // If no delivery record exists, create one (though this should ideally not happen in a real system)
        return addDeliveryUpdate(orderId, null, null, newStatus, null, "System updated status");
    }
    
    public void updateOrderStatusFromDelivery(Long orderId, String deliveryStatus) {
        // Find the associated order
        Order order = orderRepository.findById(orderId)
            .orElseThrow(() -> new RuntimeException("Order not found"));
        
        // Map delivery status to order status
        Order.OrderStatus newOrderStatus = mapDeliveryStatusToOrderStatus(deliveryStatus);
        
        if (newOrderStatus != null) {
            order.setOrderStatus(newOrderStatus);
            order.setUpdatedAt(java.time.LocalDateTime.now());
            orderRepository.save(order);
        }
    }
    
    private Order.OrderStatus mapDeliveryStatusToOrderStatus(String deliveryStatus) {
        switch (deliveryStatus.toLowerCase()) {
            case "shipped":
            case "in transit":
            case "out for delivery":
                return Order.OrderStatus.SHIPPED;
            case "delivered":
                return Order.OrderStatus.DELIVERED;
            case "cancelled":
            case "return to sender":
                return Order.OrderStatus.CANCELLED;
            default:
                // Don't change order status for other delivery statuses
                return null;
        }
    }
}